﻿using System.Data;
using System.Windows.Forms;
using CSW.Framework.Common;
using CSW.Framework.Common.Utils.ExcelUtils;

namespace CSW.Framework.UI
{
    /// <summary>
    /// Excel Utils.
    /// </summary>
    public class ExcelUtils
    {
        /// <summary>
        /// Prompts the use to load an excel file.
        /// </summary>
        /// <param name="expectedColumnCount">The expected column count.</param>
        public static DataTable GetExcelDataTable(int expectedColumnCount)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel Files (*.xls)|*.xls";
            openFileDialog.FilterIndex = 0;

            return GetExcelDataTable(expectedColumnCount, openFileDialog);
        }

        /// <summary>
        /// Prompts the use to load an excel file.
        /// </summary>
        /// <param name="expectedColumnCount">The expected column count.</param>
        /// <param name="openFileDialog">The open file dialog.</param>
        public static DataTable GetExcelDataTable(int expectedColumnCount, OpenFileDialog openFileDialog)
        {
            Guard.ArgumentNotNull(openFileDialog, "openFileDialog");

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            DataSet ds = Excel.ReadFile(openFileDialog.FileName, true);

            // User Aborted
            if (ds == null)
            {
                return null;
            }

            DataTable dt = null;
            foreach (DataTable xldt in ds.Tables)
            {
                if (xldt.Rows.Count != 0)
                {
                    if (dt == null)
                    {
                        dt = xldt;
                    }
                    else
                    {
                        MessageBox.Show("Multiple worksheets found.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return null;
                    }
                }
            }

            if (dt == null)
            {
                MessageBox.Show("No worksheet found.", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return null;
            }

            if (dt.Columns.Count != expectedColumnCount)
            {
                MessageBox.Show(string.Format("{0} columns expected, {1} columns found.", expectedColumnCount, dt.Columns.Count), "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return null;
            }

            return dt;
        }
    }
}
